﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using AmazonDynamoDBStub.Models;
using AmazonDynamoDBStub.Repositories;

namespace AmazonDynamoDBStub.EntityFramework
{
    public class RepositoryBase<TModel> : IRepository<TModel> where TModel : class
    {
        private readonly DbContext context;

        protected DbSet<TModel> DbSet
        {
            get
            {
                return context.Set<TModel>();
            }
        }

        public RepositoryBase(DbContext context)
        {
            this.context = context;
        }

        public virtual TModel FindBy(params object[] keyValues)
        {
            return context.Set<TModel>().Find(keyValues);
        }

        public virtual IEnumerable<TModel> FindAll()
        {
            return context.Set<TModel>();
        }

        public virtual IEnumerable<TModel> FindAll(Expression<Func<TModel, bool>> predicate)
        {
            return context.Set<TModel>().Where(predicate);
        }

        public virtual void Add(TModel model)
        {
            context.Set<TModel>().Add(model);
            context.SaveChanges();
        }

        public virtual void Update(TModel model)
        {
            context.Entry<TModel>(model).State = EntityState.Modified;
            context.SaveChanges();
        }

        public virtual void Remove(TModel model)
        {
            context.Set<TModel>().Remove(model);
            context.SaveChanges();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
    }
}
